package com.demo.test.juc.threadLocal;


import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

class House{
    ThreadLocal<Integer> saleNum = ThreadLocal.withInitial(() -> 0);
    public void setSaleNum(){
        saleNum.set(saleNum.get() + 1);
    }

}
/**
 * @author gy
 * @date 2023/7/29
 */
public class ThreadLocalDemo {

    static int THREAD_NUM = 5;
    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();

        House house = new House();
        AtomicInteger sum = new AtomicInteger(0);
        CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);

        for (int i = 1; i <= THREAD_NUM; i++) {
            new Thread(() -> {
                try {
                    for (int j = 1; j <= new Random().nextInt(5); j++) {
                        house.setSaleNum();;
                    }
                    System.out.println(Thread.currentThread().getName()+"\t"+"号卖出："+ house.saleNum.get());
                } finally {
                    sum.getAndAdd(house.saleNum.get());
                    house.saleNum.remove();// 变量回收，避免内存泄漏
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        // ThreadLocal 设计的目的就是为了能够在当前线程中有属于自己的变量，所以 并不能直接算出所有线程的总数
//        System.out.println(Thread.currentThread().getName()+"\t"+"共计卖出：" + house.saleNum.get());
        System.out.println(Thread.currentThread().getName()+"\t"+"共计卖出：" + sum.get());

        long endTime = System.currentTimeMillis();
        System.out.println("执行耗时["+(endTime - startTime)+"]毫秒");
    }
}
